#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:删除序列相同元素并保持顺序
问题: 怎样在一个序列上面保持元素顺序的同时消除重复的值？
提示 : 
"""


def dedupe(items):
    """元素都是hashable"""
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)


def dedupe2(items, key=None):
    """元素不是hashable的时候"""
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)


def recipe1():
    a = [1, 5, 2, 1, 9, 1, 5, 10]
    print(f"{a = }")
    print(f"{list(dedupe(a)) = }")


def recipe2():
    a = [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {
        'x': 1, 'y': 2}, {'x': 2, 'y': 4}]  # 列表+字典
    print(f"{a = }")

    # key参数指定了一个函数，将序列元素转换成 hashable 类型
    print(f"{list(dedupe2(a, key=lambda d: (d['x'], d['y']))) = }")
    print(f"{list(dedupe2(a, key=lambda d: (d['x']))) = }")


def recipe3():
    """如果仅仅就是想消除重复元素，通常可以简单的构造一个集合"""
    a = [1, 5, 2, 1, 9, 1, 5, 10]
    print(f"{a = }")
    print(f"{set(a) = }")


def recipe4():
    """生成器函数让我们的函数更加通用，不仅仅是局限于列表处理"""
    with open(r'../somefile.txt') as f:
        for line in dedupe(f):
            print(f"{line = }")


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main()
